package com.ahstu.learning.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ahstu.learning.R;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import static com.ahstu.learning.R.id.et_phoneNum;
import static com.ahstu.learning.R.id.et_register_code;
import static com.ahstu.learning.R.id.register_phone_next;


/**
 * Created by Administrator on 2016/11/15.
 */

public class RegisterPhoneActivity extends Activity implements View.OnClickListener {

    //倒计时秒数
    int i = 30;
    //短信验证监听，发送handler
    EventHandler eventHandler = new EventHandler() {
        @Override
        public void afterEvent(int event, int result, Object data) {
            Message msg = new Message();
            msg.arg1 = event;
            msg.arg2 = result;
            msg.obj = data;
            handler.sendMessage(msg);
        }
    };
    // 手机号输入框
    private EditText inputPhoneEt;
    //标题返回按钮
    private ImageView register_phone_back;
    // 验证码输入框
    private EditText inputCodeEt;
    // 获取验证码按钮
    private Button requestCodeBtn;
    /**
     *handler接收短信验证消息，更新验证按钮状态
     */
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -0x09) {
                requestCodeBtn.setText("重新发送(" + i + ")");
            } else if (msg.what == -0x08) {
                requestCodeBtn.setText("获取验证码");
                requestCodeBtn.setClickable(true);
                i = 30;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event);
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后，返回MainActivity,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                        Toast.makeText(getApplicationContext(), "提交验证码成功",
                                Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(RegisterPhoneActivity.this,RegisterActivity.class));
                        finish();
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Toast.makeText(getApplicationContext(), "验证码已经发送",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };
    // 注册按钮
    private Button commitBtn;
    private TextView register_rule;
    private CheckBox register_phone_checkbox;

    /**
     * 判断一个字符串的位数
     *
     * @param str
     * @param length
     * @return
     */
    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        } else {
            return str.length() == length ? true : false;
        }
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobileNums) {
        /*
		 * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
		 * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
		 * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
		 */
        String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_phone);

        init();

    }
    
    private void init() {
        // 启动短信验证sdk
        SMSSDK.initSDK(this, "1900b8503ecc6", "536b15a17431b61549d2c22d7c5b31c5");

        //注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);

        register_phone_back= (ImageView) findViewById(R.id.register_phone_title_back);
        inputPhoneEt= (EditText) findViewById(et_phoneNum);
        inputCodeEt= (EditText) findViewById(et_register_code);
        requestCodeBtn= (Button) findViewById(R.id.btn_register_code);
        commitBtn= (Button) findViewById(register_phone_next);
        register_rule= (TextView) findViewById(R.id.register_rule);
        register_phone_checkbox= (CheckBox) findViewById(R.id.register_phone_checkbox);

        requestCodeBtn.setOnClickListener(this);
        register_phone_back.setOnClickListener(this);
        commitBtn.setOnClickListener(this);
        register_rule.setOnClickListener(this);
        register_phone_checkbox.setOnClickListener(this);

        register_phone_checkbox.setChecked(false);
    }

    @Override
    public void onClick(View v) {
        String phoneNums = inputPhoneEt.getText().toString().trim();
        switch (v.getId()){
            case register_phone_next:
                SMSSDK.submitVerificationCode("86", phoneNums, inputCodeEt
                        .getText().toString());
                break;
            case R.id.register_phone_title_back:
                finish();
                break;
            case R.id.btn_register_code:
                // 1. 通过规则判断手机号
                if (!judgePhoneNums(phoneNums)) {
                    return;
                }
                // 2. 通过sdk发送短信验证
                SMSSDK.getVerificationCode("86", phoneNums);
                //语音验证验证码
//                SMSSDK.getVoiceVerifyCode("86",phoneNums);
                // 3. 把按钮变成不可点击，并且显示倒计时（正在获取）
                requestCodeBtn.setClickable(false);
                requestCodeBtn.setText("重新发送(" + i + ")");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (; i > 0; i--) {
                            handler.sendEmptyMessage(-0x09);
                            if (i <= 0) {
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        handler.sendEmptyMessage(-0x08);
                    }
                }).start();

                break;
            case R.id.register_rule:
                startActivity(new Intent(this, RegisterLawsActivity.class));
                break;
            case R.id.register_phone_checkbox:
                if (!register_phone_checkbox.isChecked()) {
                    commitBtn.setEnabled(false);
                    commitBtn.setBackgroundResource(R.drawable.login_button_unchecked);
                } else {
                    commitBtn.setEnabled(true);
                    commitBtn.setBackgroundResource(R.drawable.login_button);
                }
                break;
        }

    }

    /**
     * 判断手机号码是否合理
     *
     * @param phoneNums
     */
    private boolean judgePhoneNums(String phoneNums) {
        if (isMatchLength(phoneNums, 11)
                && isMobileNO(phoneNums)) {
            return true;
        }
        Toast.makeText(this, "手机号码输入有误！",Toast.LENGTH_SHORT).show();
        return false;
    }

    @Override
    protected void onDestroy() {
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();
    }

    
}
